<template>
  <div id="app">
    <h1>{{ message }}</h1>
    <form action="/fruits" method="post" @submit.prevent="postData">
      <input type="text" name="fruit" v-model="fruit" id="">
      <button>添加</button>
    </form>
    <ul>
      <li v-for="(item,index) in fruitsList" :key="index">
        {{item}}
        <button @click="handleDelItemChange(index)">删除</button>
      </li>
    </ul>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      message: "水果列表",
      fruitsList:[],
      fruit:''
    };
  },
  methods: {
    postData(){
      if(!this.fruit){
        return alert("请输入要添加的水果")
      }
      axios.post("http://127.0.0.1:7001/fruits",{fruit:this.fruit})
      .then(() => {
        this.getFruitList()
        this.fruit = ""
      })
    },
    getFruitList(){
      axios.get("http://127.0.0.1:7001/fruits").then((res) => {
        this.fruitsList = res.data;
      })
    },
    handleDelItemChange(i){
      axios.delete(`http://127.0.0.1:7001/fruits/${i}`)
      .then(() => {
        this.getFruitList()
        })
    }
  },
  created() {
    this.getFruitList()
  },
};
</script>

<style>
</style>
